import crypto from "crypto"; // nodejs自带模块
/* 四位随机数 */
export const uuid4 = function() {
  return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1);
};

/* md5加密 */
export const md5 = function(str) {
  let result;
  let md5 = crypto.createHash("md5");
  md5.update(str);
  result = md5.digest("hex");
  return result;
};

/* 倒计时方法 */
export const countDown = function(key, value_default, delay) {
  const vm = this;
  function apply() {
    vm[key]--;
    if (vm[key] > 0) {
      setTimeout(apply, delay);
    } else {
      vm[key] = value_default;
    }
  }
  apply();
};

/* 深拷贝 */
export const deepCopy = function(o) {
  if (o instanceof Array) {
    //先判断Array
    var n = [];
    for (var i = 0; i < o.length; ++i) {
      n[i] = deepCopy(o[i]);
    }
    return n;
  } else if (o instanceof Object) {
    var n = {};
    for (var i in o) {
      n[i] = deepCopy(o[i]);
    }
    return n;
  } else {
    return o;
  }
};

/* 防抖 */
export const debounce = function(fn, delay = 300) {
  let args1 = Array.prototype.slice.call(arguments, 2),
    timer = null;
  return function() {
    let context = this;
    let args2 = args1.concat(Array.prototype.slice.call(arguments));
    // console.log(args2);
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args2);
    }, delay);
  };
};

/* 节流 */
export const throttle = function(fn, delay = 300) {
  let cando = true,
    timer = null,
    args1 = Array.prototype.slice.call(arguments, 2);
  return function() {
    let context = this;
    let args2 = args1.concat(Array.prototype.slice.call(arguments));
    if (cando) {
      fn.apply(context, args2);
      cando = false;
      if (!timer) {
        timer = setTimeout(function() {
          cando = true;
          timer = null;
        }, delay);
      }
    }
  };
};

/* 时间格式化 */
export const dateFormat = function(date, fmt) {
  if (!date) return "";
  date = new Date(date);
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};

/** 将base64转换为文件对象
 *  @param {String} base64 base64字符串
 * */
export const convertBase64ToBlob = function(base64) {
  var base64Arr = base64.split(",");
  var imgtype = "";
  var base64String = "";
  if (base64Arr.length > 1) {
    //如果是图片base64，去掉头信息
    base64String = base64Arr[1];
    imgtype = base64Arr[0].substring(
      base64Arr[0].indexOf(":") + 1,
      base64Arr[0].indexOf(";")
    );
  }
  // 将base64解码
  var bytes = atob(base64String);
  //var bytes = base64;
  var bytesCode = new ArrayBuffer(bytes.length);
  // 转换为类型化数组
  var byteArray = new Uint8Array(bytesCode);

  // 将base64转换为ascii码
  for (var i = 0; i < bytes.length; i++) {
    byteArray[i] = bytes.charCodeAt(i);
  }

  // 生成Blob对象（文件对象）
  return new Blob([bytesCode], { type: imgtype });
};
